<template>
    <div class="tag-manage">
        <div class="manage-header">
            <h2>标签管理</h2>
            <div class="header-actions">
                <div class="search-container">
                    <el-input v-model="searchKeyword" placeholder="搜索标签名称" class="search-input" clearable
                        @clear="getTagList" @keyup.enter="getTagList">
                    </el-input>
                    <el-button type="primary" @click="getTagList" class="search-button">
                        <el-icon>
                            <search />
                        </el-icon>
                        搜索
                    </el-button>
                </div>
                <el-button type="primary" @click="openAddDialog" class="add-button">
                    <el-icon>
                        <plus />
                    </el-icon> 新增标签
                </el-button>
            </div>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tagList" border v-loading="loading" class="tag-table">
            <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
            <el-table-column prop="name" label="标签名称" width="180"></el-table-column>
            <el-table-column prop="categoryPath" label="所属分类" min-width="150">
                <template #default="scope">
                    <el-tag size="small" type="info" effect="plain" class="category-tag" v-if="scope.row.categoryPath">
                        {{ scope.row.categoryPath }}
                    </el-tag>
                    <el-tag size="small" type="info" effect="plain" class="category-tag"
                        v-else-if="scope.row.mcName && scope.row.scName">
                        {{ scope.row.mcName }} > {{ scope.row.scName }}
                    </el-tag>
                    <el-tag size="small" type="info" effect="plain" class="category-tag" v-else-if="scope.row.mcName">
                        {{ scope.row.mcName }}
                    </el-tag>
                    <el-tag size="small" type="info" effect="plain" class="category-tag" v-else-if="scope.row.scName">
                        {{ scope.row.scName }}
                    </el-tag>
                    <span v-else class="no-category">暂无分类</span>
                </template>
            </el-table-column>
            <el-table-column prop="useCount" label="使用次数" width="120" align="center"></el-table-column>
            <el-table-column prop="sortOrder" label="排序" width="80" align="center"></el-table-column>
            <el-table-column label="热门标签" width="100" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.isHot ? 'danger' : 'info'" effect="dark">
                        {{ scope.row.isHot ? '热门' : '普通' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="状态" width="100" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" effect="dark">
                        {{ scope.row.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right" align="center">
                <template #default="scope">
                    <div class="table-actions">
                        <el-tooltip content="编辑" placement="top">
                            <el-button size="small" type="primary" @click="handleEdit(scope.row)" circle>
                                <el-icon>
                                    <edit />
                                </el-icon>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip content="删除" placement="top">
                            <el-button size="small" type="danger" @click="handleDelete(scope.row)" circle>
                                <el-icon>
                                    <delete />
                                </el-icon>
                            </el-button>
                        </el-tooltip>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 空数据展示 -->
        <el-empty v-if="tagList.length === 0 && !loading" description="暂无标签数据" class="empty-data">
            <el-button type="primary" @click="openAddDialog">
                <el-icon>
                    <plus />
                </el-icon> 添加标签
            </el-button>
        </el-empty>

        <!-- 分页组件 -->
        <el-pagination v-if="tagList.length > 0" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="pagination.currentPage" :page-sizes="[10, 20, 30, 50]" :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" background class="pagination">
        </el-pagination>

        <!-- 新增/编辑对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="600px" @closed="resetForm" destroy-on-close
            class="tag-dialog" :close-on-click-modal="false">
            <div class="dialog-content">
                <el-form :model="tagForm" :rules="rules" ref="tagForm" label-width="100px" class="tag-form">
                    <el-form-item label="标签名称" prop="name">
                        <el-input v-model="tagForm.name" placeholder="请输入标签名称" maxlength="20"
                            show-word-limit></el-input>
                    </el-form-item>

                    <el-form-item label="所属分类" prop="mcId">
                        <el-cascader v-model="selectedCategory" :options="categoryOptions" :props="{
                            value: 'id',
                            label: 'name',
                            children: 'children',
                            checkStrictly: false,
                            emitPath: true
                        }" placeholder="请选择所属分类" class="category-cascader" @change="handleCategoryChange" clearable>
                            <template #default="{ node, data }">
                                <span>{{ data.name }}</span>
                                <span v-if="!node.isLeaf" style="color: #999; font-size: 12px;">
                                    ({{ data.children?.length || 0 }}个子分类)
                                </span>
                            </template>
                        </el-cascader>
                        <div class="selected-category" v-if="tagForm.mcId && tagForm.mcName">
                            <span>已选: {{ tagForm.mcName }}</span>
                            <span v-if="tagForm.scName"> > {{ tagForm.scName }}</span>
                        </div>
                    </el-form-item>

                    <el-form-item label="排序" prop="sortOrder">
                        <el-input-number v-model="tagForm.sortOrder" :min="1" :max="999"
                            controls-position="right"></el-input-number>
                        <span class="form-tip">数值越小越靠前</span>
                    </el-form-item>

                    <el-form-item label="热门标签" prop="isHot">
                        <el-switch v-model="tagForm.isHot" active-text="热门" inactive-text="普通" :active-value="true"
                            :inactive-value="false" inline-prompt>
                        </el-switch>
                    </el-form-item>

                    <el-form-item label="状态" prop="status">
                        <el-switch v-model="tagForm.status" :active-value="1" :inactive-value="0" active-text="启用"
                            inactive-text="禁用" inline-prompt class="status-switch">
                        </el-switch>
                    </el-form-item>

                    <el-form-item label="标签描述" prop="description">
                        <el-input type="textarea" v-model="tagForm.description" :rows="3" placeholder="请输入标签描述"
                            maxlength="200" show-word-limit></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false" plain>取 消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitting" :disabled="submitting">
                        {{ submitting ? '提交中...' : '确 定' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "TagManage",
    data() {
        return {
            loading: false,
            submitting: false, // 提交表单的加载状态
            tagList: [],
            searchKeyword: "",
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            },
            dialogVisible: false,
            dialogTitle: "新增标签",
            tagForm: {
                id: null,
                name: "",
                mcId: "",
                scId: "",
                mcName: "",
                scName: "",
                isHot: false,
                sortOrder: 1,
                status: 1,
                description: ""
            },
            rules: {
                name: [
                    { required: true, message: "请输入标签名称", trigger: "blur" },
                    { max: 20, message: "长度不能超过20个字符", trigger: "blur" }
                ],
                mcId: [
                    { required: true, message: "请选择所属分类", trigger: "change" }
                ],
                scId: [
                    { required: true, message: "请选择子分类", trigger: "change" }
                ]
            },
            selectedCategory: [],
            categoryOptions: [],
            uploadHeaders: {
                Authorization: `Bearer ${localStorage.getItem('teri_token') || ''}`
            }
        };
    },
    created() {
        this.getTagList();
        this.getCategoryOptions();
    },
    methods: {
        // 获取标签列表
        async getTagList() {
            this.loading = true;
            try {
                const res = await this.$get("/admin/tag/list", {
                    params: {
                        keyword: this.searchKeyword,
                        page: this.pagination.currentPage,
                        pageSize: this.pagination.pageSize
                    }
                });

                if (res.data.code === 200) {
                    this.tagList = res.data.data.records || [];
                    this.pagination.total = res.data.data.total || 0;

                    // 调试信息
                    console.log("标签数据:", this.tagList);
                } else {
                    this.$message.error(res.data.message || "获取标签列表失败");
                }
            } catch (error) {
                console.error("获取标签列表错误:", error);
                this.$message.error("网络错误，获取标签列表失败");
            } finally {
                this.loading = false;
            }
        },

        // 获取分类选项
        async getCategoryOptions() {
            try {
                const res = await this.$get("/admin/category/tree");
                if (res.data.code === 200 && Array.isArray(res.data.data)) {
                    this.categoryOptions = res.data.data;
                    console.log("分类选项:", this.categoryOptions);
                } else {
                    console.error("获取分类选项失败:", res.data.message);
                    // 尝试使用备用方式获取分类
                    await this.getCategoryOptionsFallback();
                }
            } catch (error) {
                console.error("获取分类选项错误:", error);
                this.$message.error("网络错误，获取分类选项失败");
                // 尝试使用备用方式获取分类
                await this.getCategoryOptionsFallback();
            }
        },

        // 备用方式获取分类选项
        async getCategoryOptionsFallback() {
            try {
                const res = await this.$get("/category/getall");
                if (res.data.code === 200 && Array.isArray(res.data.data)) {
                    // 将响应数据转换为级联选择器所需格式
                    this.categoryOptions = res.data.data.map(mc => {
                        return {
                            id: mc.mcId,
                            name: mc.mcName,
                            children: Array.isArray(mc.scList) ? mc.scList.map(sc => {
                                return {
                                    id: sc.scId,
                                    name: sc.scName
                                };
                            }) : []
                        };
                    });
                    console.log("备用方式分类选项:", this.categoryOptions);
                } else {
                    this.$message.error(res.data.message || "获取分类选项备用方式失败");
                }
            } catch (error) {
                console.error("获取分类选项备用方式错误:", error);
                this.$message.error("网络错误，获取分类选项备用方式失败");
            }
        },

        // 处理分类选择变化
        handleCategoryChange(value) {
            console.log("分类选择变更:", value);
            if (value && value.length >= 2) {
                // 获取主分类和子分类的ID
                this.tagForm.mcId = value[0];
                this.tagForm.scId = value[1];

                // 查找对应的名称
                const mainCategory = this.categoryOptions.find(item => item.id === value[0]);
                if (mainCategory) {
                    this.tagForm.mcName = mainCategory.name;
                    const subCategory = mainCategory.children?.find(item => item.id === value[1]);
                    if (subCategory) {
                        this.tagForm.scName = subCategory.name;
                    }
                }

                // 手动验证
                this.$nextTick(() => {
                    this.$refs.tagForm.validateField('mcId');
                    this.$refs.tagForm.validateField('scId');
                });
            } else if (value && value.length === 1) {
                this.tagForm.mcId = value[0];
                this.tagForm.scId = "";

                // 查找对应的名称
                const mainCategory = this.categoryOptions.find(item => item.id === value[0]);
                if (mainCategory) {
                    this.tagForm.mcName = mainCategory.name;
                    this.tagForm.scName = "";
                }
            } else {
                this.tagForm.mcId = "";
                this.tagForm.scId = "";
                this.tagForm.mcName = "";
                this.tagForm.scName = "";
            }
        },

        // 打开新增对话框
        openAddDialog() {
            this.dialogTitle = "新增标签";
            this.resetForm();
            this.dialogVisible = true;
        },

        // 处理编辑
        async handleEdit(row) {
            this.dialogTitle = "编辑标签";
            this.resetForm();
            try {
                const res = await this.$get(`/admin/tag/${row.id}`);
                if (res.data.code === 200) {
                    const tagData = res.data.data;
                    this.tagForm = { ...tagData };
                    this.selectedCategory = [tagData.mcId, tagData.scId].filter(Boolean);
                    this.dialogVisible = true;

                    console.log("编辑标签数据:", this.tagForm);
                    console.log("编辑标签分类:", this.selectedCategory);
                } else {
                    this.$message.error(res.data.message || "获取标签详情失败");
                }
            } catch (error) {
                console.error("获取标签详情错误:", error);
                this.$message.error("网络错误，获取标签详情失败");
            }
        },

        // 处理删除
        handleDelete(row) {
            this.$confirm("确认删除该标签?", "提示", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "warning"
            }).then(async () => {
                try {
                    const res = await this.$axios({
                        method: 'delete',
                        url: `/api/admin/tag/${row.id}`,
                        headers: {
                            'Authorization': `Bearer ${localStorage.getItem('teri_token') || ''}`
                        }
                    });

                    if (res.data.code === 200) {
                        this.$message.success("删除成功");
                        this.getTagList();
                    } else {
                        this.$message.error(res.data.message || "删除失败");
                    }
                } catch (error) {
                    console.error("删除标签错误:", error);
                    this.$message.error("网络错误，删除失败");
                }
            }).catch(() => { });
        },

        // 提交表单
        submitForm() {
            console.log("提交的表单数据:", this.tagForm);
            console.log("选择的分类:", this.selectedCategory);

            this.$refs.tagForm.validate(async valid => {
                if (valid) {
                    // 确保分类ID已设置
                    if (!this.tagForm.mcId || !this.tagForm.scId) {
                        this.$message.error("请选择完整的所属分类");
                        return;
                    }

                    this.submitting = true;
                    const isEdit = this.tagForm.id !== null;
                    const method = isEdit ? "put" : "post";
                    const url = isEdit ? `/admin/tag/${this.tagForm.id}` : "/admin/tag";

                    try {
                        const res = await this.$axios({
                            method: method,
                            url: `/api${url}`,
                            data: this.tagForm,
                            headers: {
                                'Content-Type': 'application/json',
                                'Authorization': `Bearer ${localStorage.getItem('teri_token') || ''}`
                            }
                        });

                        if (res.data.code === 200) {
                            this.$message.success(isEdit ? "更新成功" : "添加成功");
                            this.dialogVisible = false;
                            this.getTagList();
                        } else {
                            this.$message.error(res.data.message || (isEdit ? "更新失败" : "添加失败"));
                        }
                    } catch (error) {
                        console.error(isEdit ? "更新错误:" : "添加错误:", error);
                        this.$message.error(isEdit ? "更新失败" : "添加失败");
                    } finally {
                        this.submitting = false;
                    }
                } else {
                    console.error("表单验证失败");
                }
            });
        },

        // 重置表单
        resetForm() {
            if (this.$refs.tagForm) {
                this.$refs.tagForm.resetFields();
            }
            this.tagForm = {
                id: null,
                name: "",
                mcId: "",
                scId: "",
                mcName: "",
                scName: "",
                isHot: false,
                sortOrder: 1,
                status: 1,
                description: ""
            };
            this.selectedCategory = [];
        },

        // 处理分页大小变化
        handleSizeChange(size) {
            this.pagination.pageSize = size;
            this.pagination.currentPage = 1;
            this.getTagList();
        },

        // 处理页码变化
        handleCurrentChange(page) {
            this.pagination.currentPage = page;
            this.getTagList();
        }
    }
}
</script>

<style scoped>
.tag-manage {
    padding: 30px;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    min-height: calc(100vh - 120px);
    margin: 20px;
}

.manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;
}

.manage-header h2 {
    font-size: 22px;
    font-weight: 600;
    color: #333;
    margin: 0;
    position: relative;
    padding-left: 14px;
}

.manage-header h2::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 22px;
    background-color: #409EFF;
    border-radius: 2px;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 15px;
}

.search-container {
    display: flex;
    align-items: center;
    gap: 12px;
}

.search-input {
    width: 250px;
    border-radius: 4px;
}

.search-button {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 8px 16px;
    border-radius: 4px;
    box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
    font-weight: 500;
    transition: all 0.3s ease;
}

.search-button:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    opacity: 0.9;
}

.add-button {
    padding: 9px 16px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 6px;
}

/* 表格样式 */
.tag-table {
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 20px;
    border: 1px solid #ebeef5;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.03);
}

/* 表格操作按钮样式 */
.table-actions {
    display: flex;
    justify-content: center;
    gap: 12px;
}

/* 分类标签样式 */
.category-tag {
    padding: 4px 8px;
    font-size: 12px;
    display: inline-flex;
    align-items: center;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    height: auto;
    line-height: 1.5;
    background-color: #f8f9fb;
    border: 1px solid #ebeef5;
    color: #606266;
    border-radius: 4px;
}

.category-tag:hover {
    background-color: #f0f2f5;
    color: #409EFF;
}

.selected-category {
    margin-top: 8px;
    font-size: 13px;
    color: #606266;
    padding: 4px 8px;
    background-color: #f8f9fb;
    border-radius: 4px;
    display: inline-block;
}

.no-category {
    color: #909399;
    font-size: 12px;
    font-style: italic;
}

/* 分页样式 */
.pagination {
    margin-top: 24px;
    text-align: right;
    padding: 12px 0;
}

/* 空数据样式 */
.empty-data {
    margin: 80px auto;
    text-align: center;
}

/* 对话框样式 */
:deep(.tag-dialog) {
    border-radius: 8px;
    overflow: hidden;
}

:deep(.tag-dialog .el-dialog__header) {
    padding: 20px 24px;
    margin-bottom: 0;
    position: relative;
    border-bottom: 1px solid #f0f0f0;
}

:deep(.tag-dialog .el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

:deep(.tag-dialog .el-dialog__headerbtn) {
    top: 20px;
}

:deep(.tag-dialog .el-dialog__body) {
    padding: 24px;
}

:deep(.tag-dialog .el-dialog__footer) {
    padding: 16px 24px;
    border-top: 1px solid #f0f0f0;
    display: flex;
    justify-content: center;
}

.dialog-content {
    max-height: 60vh;
    overflow-y: auto;
    overflow-x: hidden;
    padding-right: 5px;
}

/* 滚动条样式 */
.dialog-content::-webkit-scrollbar {
    width: 6px;
}

.dialog-content::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
}

.dialog-content::-webkit-scrollbar-track {
    background-color: #f5f5f5;
    border-radius: 3px;
}

.tag-form {
    width: 100%;
}

/* 表单项样式 */
:deep(.el-form-item) {
    margin-bottom: 22px;
}

:deep(.el-form-item__label) {
    font-weight: 500;
}

.form-tip {
    color: #909399;
    font-size: 13px;
    margin-left: 10px;
}

.category-cascader {
    width: 100%;
}

/* 按钮样式 */
.dialog-footer {
    display: flex;
    justify-content: center;
    gap: 16px;
}

.dialog-footer .el-button {
    padding: 10px 24px;
    min-width: 100px;
    font-size: 14px;
    font-weight: 500;
}

.status-switch {
    width: 90px;
}
</style>